package com.pipi.biyesheji.service.impl;

import com.pipi.biyesheji.dao.manager.UserRoleManager;
import com.pipi.biyesheji.dao.model.UserRoleDO;
import com.pipi.biyesheji.dao.query.UserRoleQuery;
import com.pipi.biyesheji.pojo.User;
import com.pipi.biyesheji.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author pipi
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {


    @Autowired
    private UserRoleManager userRoleManager;

    @Override
    public void setRoles(User user, long[] roleIds) {
        //删除当前管理员所有的角色
        UserRoleQuery userRoleQuery = new UserRoleQuery();
        userRoleQuery.createCriteria().andUidEqualTo(user.getId());
        List<UserRoleDO> userRoleDOS = userRoleManager.selectByQuery(userRoleQuery);

        for (UserRoleDO userRoleDO : userRoleDOS) {
            userRoleManager.deleteByPrimaryKey(userRoleDO.getId());
        }

        //设置新的角色关系
        if(null!=roleIds) {
            for (long rid : roleIds) {
                UserRoleDO userRoleDO = new UserRoleDO();
                userRoleDO.setRid(rid);
                //插入管理员新的所有权限
                userRoleDO.setUid(user.getId());
                userRoleManager.insertSelective(userRoleDO);
            }
        }
    }

    @Override
    public void deleteByUser(long userId) {
        UserRoleQuery userRoleQuery = new UserRoleQuery();
        userRoleQuery.createCriteria().andUidEqualTo(userId);
        List<UserRoleDO> userRoleDOS = userRoleManager.selectByQuery(userRoleQuery);
        //依次删除记录
        for (UserRoleDO userRoleDO : userRoleDOS) {
            userRoleManager.deleteByPrimaryKey(userRoleDO.getId());
        }
    }

    @Override
    public void deleteByRole(long roleId) {
        UserRoleQuery userRoleQuery = new UserRoleQuery();
        userRoleQuery.createCriteria().andRidEqualTo(roleId);
        //查询UserRole表为角色id的记录  下面删除
        List<UserRoleDO> userRoleDOS = userRoleManager.selectByQuery(userRoleQuery);
        for (UserRoleDO userRoleDO : userRoleDOS) {
            userRoleManager.deleteByPrimaryKey(userRoleDO.getId());
        }
    }
}
